package com.atguigu.gulimall.coupon.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class CouponSentinelConfig {

    @Bean
    public BlockExceptionHandler blockExceptionHandler() {
        return new BlockExceptionHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
                // 自定义处理逻辑
                // response.setContentType("application/json;charset=utf-8");
                // response.setStatus(429); // 返回429 Too Many Requests
                // response.getWriter().println("{\"code\": 429, \"msg\": \"请求被限流\"}");
                R r = R.error(BizCodeEnum.TOO_MANY_REQUEST_EXCEPTION.getCode(), BizCodeEnum.TOO_MANY_REQUEST_EXCEPTION.getMsg());
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSONUtil.toJsonStr(r));
            }
        };
    }

    @Bean
    public SentinelWebMvcConfig MySentinelWebMvcConfig(BlockExceptionHandler handler) {
        SentinelWebMvcConfig config = new SentinelWebMvcConfig();
        config.setBlockExceptionHandler(handler);
        return config;
    }
}